package com.zhuzg.aop;

import com.zhuzg.annotation.MesCache;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
//import org.springframework.data.redis.core.RedisTemplate;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.concurrent.TimeUnit;

@Aspect
@Component
public class CacheInterceptor {

   // @Autowired
  ///  RedisTemplate redisTemplate;

    @Around("@annotation(com.zhuzg.annotation.MesCache)")
    public  Object myCache(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("拦截器被执行");

        MethodSignature methodSignature = (MethodSignature) pjp.getSignature();
        // 获取到方法
        Method method = methodSignature.getMethod();
        // 获取注解
        MesCache mesCache = method.getAnnotation(MesCache.class);
        int expiretime = mesCache.expiretime();
        String key = mesCache.key();
        String para = mesCache.para();
        System.out.println(String.format("key is %s, expiretime is %d ,para is %s",key,expiretime,para));

        // 判断那个参数的名称与para 相同  。
        Parameter[] parameters = method.getParameters();
        int paraIndex=-1;
        for (int i = 0; i < parameters.length; i++) {
            if(parameters[i].getName().equals(para)){
                paraIndex=i;
                break;
            }
        }

        Object[] args = pjp.getArgs();
        String redisKey =key + ":" + args[paraIndex].toString();

        System.out.println("rediskey is " + redisKey);

        Object result = pjp.proceed();
        return result;
        //
      /*  Object[] args = pjp.getArgs();
        String redisKey =key + ":" + args[paraIndex].toString();
        if (redisTemplate.hasKey(redisKey)){
            return redisTemplate.opsForValue().get(redisKey);
        }else{
            Object result = pjp.proceed();
            redisTemplate.opsForValue().set(redisKey,result);
            redisTemplate.expire(redisKey,expiretime, TimeUnit.SECONDS);
            return result;
        }*/
    }

}
